package com.link.base.base.wechat.controller;

import com.alibaba.fastjson.JSONObject;
import com.link.base.base.mpconfig.service.MpTemplateService;
import com.link.base.base.sms.model.PushSms;
import com.link.base.sms.model.Template;
import com.link.base.base.sms.service.PushSmsService;
import com.link.base.base.sms.service.TemplateService;
import com.link.base.base.wechat.model.TemTable;
import com.link.base.base.wechat.model.SceneTempData;
import com.link.base.base.wechat.model.WxTemplate;
import com.link.base.base.wechat.service.TableService;
import com.link.base.base.wechat.service.WxTemplateService;
import com.link.base.wechat.basic.util.WeixinHttpUtil;
import com.link.base.wechat.wxplatform.model.WxPlatform;
import com.link.base.wechat.wxplatform.service.WxPlatformService;
import com.link.base.wechat.wxtoken.service.WxTokenService;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.service.BasicService;
import com.link.core.cllog.LCLogger;
import com.link.core.util.StringUtils;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * wx模板消息
 *
 * @author 路江
 * @date 2018-05
 */
@Controller
@RequestMapping("/link/wxTemplate")
public class WxTemplateController extends BasicController<WxTemplate> {
    @Resource
    private TemplateService templateService;
    @Resource
    private PushSmsService pushSmsService;
    @Resource
    private MpTemplateService mpTemplateService;
    @Resource
    private TableService tableService;

    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private WxPlatformService wxPlatformService;
    @Resource
    private WxTokenService wxTokenService;
    @Resource
    private Environment env;

    @Override
    public BasicService<WxTemplate> getBasicService() throws Exception {
        return wxTemplateService;
    }

    /**
     * 新增模板数据
     *
     * @author 闫有霞
     * @date 2018/11/29
     * @param temp
     * @return
     */
    @RequestMapping(value = "inserttemp")
    @ResponseBody
    public Map<String, Object> insertTemp(@RequestBody SceneTempData temp) {
        Map<String, Object> result = new HashMap<>(16);
        PushSms pushSms = new PushSms();
        pushSms.setId(temp.getId());
        try {
            pushSms = pushSmsService.queryById(pushSms);

            Template template = temp.getTemplate().get(0);
            for (int i = 0; i < temp.getTables().size(); i++) {
                tableService.insert(temp.getTables().get(i));
                if (i == 0) {
                    template.setParameter1(String.valueOf(temp.getTables().get(i).getId()));
                }
                if (i == 1) {
                    template.setParameter2(String.valueOf(temp.getTables().get(i).getId()));
                }
                if (i == 2) {
                    template.setParameter3(String.valueOf(temp.getTables().get(i).getId()));
                }
                if (i == 3) {
                    template.setParameter4(String.valueOf(temp.getTables().get(i).getId()));
                }
                if (i == 4) {
                    template.setParameter5(String.valueOf(temp.getTables().get(i).getId()));
                }
            }
            mpTemplateService.insert(template);
            pushSms.setWxTempId(template.getId());
            pushSmsService.update(pushSms);
            pushSms = pushSmsService.queryById(pushSms);
            result.put("success", true);
            result.put("pushSms", pushSms);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e);
            LCLogger.withException(e);
        }
        return result;

    }

    /**
     * @createdBy 闫有霞
     * @date 2018/11/29
     * @methods: upsert
     * @param: template
     * @return: Map
     * @description: 微信模板插入更新方法-先插入模板的配置参数再将
     * 配置参数的row_id 及模板其他信息插入或更新到微信模板表
     *
     **/
    @RequestMapping(value = "upsertWxTemplate")
    @ResponseBody
    public Map<String, Object> upsertWxTemplate(@RequestBody SceneTempData temp) {
        Map<String, Object> result = new HashMap<>(16);
        try {
            /*获取微信模板及其参数配置信息*/
            Template template = temp.getTemplate().get(0);
            /*查询模板参数并且遍历 插入参数表*/
            for (int i = 0; i < temp.getTables().size(); i++) {
                /*插入参数配置信息到参数配置表*/
                tableService.insert(temp.getTables().get(i));
                String paramId = String.valueOf(temp.getTables().get(i).getId());
                /*获取插入的参数配置ID 放入模板*/
                switch (i) {
                    case 0:
                        template.setParameter1(paramId);
                        break;
                    case 1:
                        template.setParameter2(paramId);
                        break;
                    case 2:
                        template.setParameter3(paramId);
                        break;
                    case 3:
                        template.setParameter4(paramId);
                        break;
                    case 4:
                        template.setParameter5(paramId);
                        break;
                    case 5:
                        template.setParameter6(paramId);
                        break;
                    case 6:
                        template.setParameter7(paramId);
                        break;
                    case 7:
                        template.setParameter8(paramId);
                        break;
                    case 8:
                        template.setParameter9(paramId);
                        break;
                    case 9:
                        template.setParameter10(paramId);
                        break;
                    default:
                        break;

                }

            }
            /*调用basic中的upsert方法当row_status=='NEW' 时执行新建
            * 当row_status=='UPDATE' 时执行更新操作*/
            mpTemplateService.upsert(template);
            result.put("success", true);
            result.put("template", template);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e);
            LCLogger.withException(e);
        }
        return result;

    }

    /**
     * 查询场景模板字段信息
     *
     * @author 闫有霞
     * @date 2018/11/29
     * @param pushSms
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "queryTable")
    @ResponseBody
    public Map<String, Object> queryTable(@JsonParam PushSms pushSms, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(16);
        try {
            Template template = templateService.queryById(pushSms.getWxTempId());
            List<TemTable> tables = new ArrayList<TemTable>();
            if (!StringUtils.isBlank(template.getParameter1())) {
                tables.add(tableService.queryById(Long.valueOf(template.getParameter1())));
            }
            if (!StringUtils.isBlank(template.getParameter2())) {
                tables.add(tableService.queryById(Long.valueOf(template.getParameter2())));
            }
            if (!StringUtils.isBlank(template.getParameter3())) {
                tables.add(tableService.queryById(Long.valueOf(template.getParameter3())));
            }
            if (!StringUtils.isBlank(template.getParameter4())) {
                tables.add(tableService.queryById(Long.valueOf(template.getParameter4())));
            }
            if (!StringUtils.isBlank(template.getParameter5())) {
                tables.add(tableService.queryById(Long.valueOf(template.getParameter5())));
            }
            result.put("success", true);
            result.put("rows", tables);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e);
            LCLogger.withException(e);
        }
        return result;

    }

    /**
     * @createdBy 闫有霞
     * @date 2018/11/29
     * @methods: queryWxTemplate
     * @param: Template
     * @return: Map tables
     * @description: 查询该模板下参数配置及服务号-用于页面编辑
     **/
    @RequestMapping(value = "queryWxTemplate")
    @ResponseBody
    public Map<String, Object> queryWxTemplate(@JsonParam Template temp, HttpSession session,
                                               HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(16);
        try {
             /*根据ID查出对应的消息模板*/
            Template template = templateService.queryById(temp.getId());
            List<TemTable> tables = new ArrayList<TemTable>();
            /*根据parameter查出对应的消息模板所对应参数配置信息*/
            if (!StringUtils.isBlank(template.getParameter1())) {
                tables.add(tableService.queryById(Long.valueOf(template.getParameter1())));
            }
            if (!StringUtils.isBlank(template.getParameter2())) {
                tables.add(tableService.queryById(Long.valueOf(template.getParameter2())));
            }
            if (!StringUtils.isBlank(template.getParameter3())) {
                tables.add(tableService.queryById(Long.valueOf(template.getParameter3())));
            }
            if (!StringUtils.isBlank(template.getParameter4())) {
                tables.add(tableService.queryById(Long.valueOf(template.getParameter4())));
            }
            if (!StringUtils.isBlank(template.getParameter5())) {
                tables.add(tableService.queryById(Long.valueOf(template.getParameter5())));
            }
            if (!StringUtils.isBlank(template.getParameter6())) {
                tables.add(tableService.queryById(Long.valueOf(template.getParameter6())));
            }
            if (!StringUtils.isBlank(template.getParameter7())) {
                tables.add(tableService.queryById(Long.valueOf(template.getParameter7())));
            }
            if (!StringUtils.isBlank(template.getParameter8())) {
                tables.add(tableService.queryById(Long.valueOf(template.getParameter8())));
            }
            if (!StringUtils.isBlank(template.getParameter9())) {
                tables.add(tableService.queryById(Long.valueOf(template.getParameter9())));
            }
            if (!StringUtils.isBlank(template.getParameter10())) {
                tables.add(tableService.queryById(Long.valueOf(template.getParameter10())));
            }
            result.put("success", true);
            result.put("tables", tables);
            result.put("template", template);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e);
            LCLogger.withException(e);
        }
        return result;

    }

    /**
     * 获取微信公众号模板消息列表
     *
     * @author lujiang
     * @date 2019-03-12
     * @param wx_id 微信列表row_id
     * @return
     */
    @RequestMapping(value = "getTemplate_list", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> getTemplateList(Long wx_id) {
        Map<String, Object> map = new HashMap<>(16);
        try {
            //从lnk_wx_platform 取出 token ,token会有微信授权模块去进行更新
            WxPlatform wxPlatform = new WxPlatform();
            wxPlatform.setId(wx_id);
            WxPlatform platform = wxPlatformService.queryById(wxPlatform);
            String accessToken = wxTokenService.getWxAccessTokenByAppId(platform.getWx_app_id()).getAccess_token();
            String url = env.getProperty("weixinuri.wxTempLateListUrl").replace("ACCESS_TOKEN", accessToken);
            JSONObject json = WeixinHttpUtil.httpRequest(url, "GET", null);
            Map<String, Object> exampleMap = new HashMap<>(16);
            String templateList = "template_list";
            if (json.containsKey(templateList)) {
                for (int i = 0; i < json.getJSONArray(templateList).size(); i++) {
                    String example = JSONObject.parseObject(json.getJSONArray("template_list").get(i).toString()).get("example").toString();
                    if (example != null && example.indexOf("\n") != -1) {
                        if (example.indexOf("\r\n") != -1) {
                            example = example.replace("\r\n", "<br/>");
                        } else {
                            example = example.replace("\n", "<br/>");
                        }
                    }
                    exampleMap.put(JSONObject.parseObject(
                            json.getJSONArray("template_list").get(i).toString()).get("template_id").toString(), example);
                }
            }
            map.put("result", json);
            map.put("example", exampleMap);
            map.put("success", true);
        } catch (Exception e) {
            map.put("success", false);
        }
        return map;
    }

    /**
     * 保存配置字段
     *
     * @author lujiang
     * @date 2018-05
     * @param table
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "insertTable", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Long insertTable(@JsonParam TemTable table) throws Exception {
        tableService.insert(table);
        return tableService.queryById(table).getId();

    }
}
